package git.soulbgm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.pojo.QueryDto;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.pojo.SoftwareInfo;
import git.soulbgm.service.SoftwareInfoService;
import git.soulbgm.service.SoftwareStatusService;
import git.soulbgm.utils.EasyPoiUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 第三方软件信息控制器
 *
 * @author SoulBGM
 * @date 2022/03/11 10:28
 */
@RestController
@RequestMapping("system/software")
public class SoftwareController extends BaseController {

    private final SoftwareInfoService softwareInfoService;
    private final SoftwareStatusService softwareStatusService;

    public SoftwareController(SoftwareInfoService softwareInfoService, SoftwareStatusService softwareStatusService) {
        this.softwareInfoService = softwareInfoService;
        this.softwareStatusService = softwareStatusService;
    }

    @PostMapping("list")
    public Response list(@RequestBody QueryDto<SoftwareInfo> dto, Page<SoftwareInfo> queryPage) {
        Page<SoftwareInfo> resultPage = softwareInfoService.page(queryPage, new QueryWrapper<>(dto.getData()));
        return success(resultPage);
    }

    @GetMapping("export")
    public void export(SoftwareInfo info, HttpServletResponse response) {
        List<SoftwareInfo> list = softwareInfoService.list(new QueryWrapper<>(info));
        try {
            EasyPoiUtil.exportExcel(response, "软件数据", list, SoftwareInfo.class);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

    @PostMapping("add")
    public Response add(SoftwareInfo info) {
        boolean result = softwareInfoService.save(info);
        if (result) {
            softwareInfoService.clearCache();
        }
        return result ? success() : error();
    }

    @PostMapping("remove")
    public Response remove(String ids) {
        boolean result = softwareInfoService.removeByIds(Arrays.asList(ids.split(",")));
        if (result) {
            softwareStatusService.removeByIds(Arrays.asList(ids.split(",")));
            softwareInfoService.clearCache();
        }
        return result ? success() : error();
    }

    @PostMapping({"changeStatus", "changeSelfStatus", "edit"})
    public Response edit(SoftwareInfo info) {
        boolean result = softwareInfoService.updateById(info);
        if (result) {
            softwareInfoService.clearCache();
        }
        return result ? success() : error();
    }
}
